package database

import (
	"gitee.com/zhucheer/orange/cfg"
	"github.com/zhuCheer/pool"
	"regexp"
	"strings"
)

type DataBase interface {
	RegisterAll()
	Register(string)
	insertPool(string, pool.Pool)
	getDB(string) (interface{}, func(), error)
	putDB(string, interface{}) error
}

// RegisterAll 注册所有支持的驱动
func RegisterAll() {
	go NewMysql().RegisterAll()
	go NewGorm().RegisterAll()
	go NewRedis().RegisterAll()
	go NewMongo().RegisterAll()
	go NewPostgre().RegisterAll()
}

// PutConn 将连接放回连接池方法
func PutConn(put func()) {
	if put == nil {
		return
	}
	put()
	return
}

func getDBIntConfig(dbtype, name, key string) int {
	exists := cfg.Config.Exists("database." + dbtype + "." + name + "." + key)
	if exists == false {
		return cfg.Config.GetInt("database." + key)
	}
	return cfg.Config.GetInt("database." + dbtype + "." + name + "." + key)
}

func getBoolConfig(dbtype, name, key string) bool {
	exists := cfg.Config.Exists("database." + dbtype + "." + name + "." + key)
	if exists == false {
		return cfg.Config.GetBool("database." + key)
	}
	return cfg.Config.GetBool("database." + dbtype + "." + name + "." + key)
}

// 隐藏连接密码日志
func hideDsnPasswordLog(dsn string) (hideDsn string) {
	hideDsn = dsn
	hideDsnData := regexp.MustCompile(`\/\/[\w]+\:(.*)@`).FindStringSubmatch(dsn)
	if len(hideDsnData) > 1 {
		hideDsn = strings.Replace(dsn, hideDsnData[1], "******", -1)
	}
	return
}

func hideTcpDsnPasswordLog(dsn string) (hideDsn string) {
	hideDsn = dsn
	hideDsnData := regexp.MustCompile(`[\w]+\:(.*)@tcp`).FindStringSubmatch(dsn)
	if len(hideDsnData) > 1 {
		hideDsn = strings.Replace(dsn, hideDsnData[1], "******", -1)
	}
	return
}
